package com.lzb.browser.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lzb.browser.BaseAc;
import com.lzb.browser.Content;
import com.lzb.browser.R;
import com.lzb.browser.adapter.CollectAdapter;
import com.lzb.browser.adapter.HotAdapter;
import com.lzb.browser.adapter.RecordAdapter;
import com.lzb.browser.adapter.SearchSuggestionAdapter;
import com.lzb.browser.bean.CollectBean;
import com.lzb.browser.bean.HomeBean;
import com.lzb.browser.bean.RecordBean;
import com.lzb.browser.bean.SearchSuggestionBean;
import com.lzb.browser.databinding.ActivitySearchBinding;
import com.lzb.browser.utils.AppSpUtils;
import com.lzb.browser.utils.OkHttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends BaseAc<ActivitySearchBinding> implements View.OnClickListener, OnItemClickListener {

    private HotAdapter hotAdapter;
    private boolean isKeyboardVisible = false;
    private SearchSuggestionAdapter suggestionAdapter;
    private RecordAdapter recordAdapter;
    private CollectAdapter collectAdapter;

    @Override
    protected int onCreate() {
        return R.layout.activity_search;
    }

    @Override
    protected void initView() {
        mDataBinding.tvSearchCancel.setOnClickListener(view -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.tvSearchGo.setOnClickListener(this);
        mDataBinding.ivClear.setOnClickListener(this);
        mDataBinding.llHot.setOnClickListener(this);
        mDataBinding.llBookmark.setOnClickListener(this);
        mDataBinding.llCollectUrl.setOnClickListener(this);
        mDataBinding.tvAllDelete.setOnClickListener(this);

        mDataBinding.rvHotList.setLayoutManager(new GridLayoutManager(mContext, 3));
        hotAdapter = new HotAdapter();
        mDataBinding.rvHotList.setAdapter(hotAdapter);
        hotAdapter.setOnItemClickListener(this);

        mDataBinding.rvSuggestionList.setLayoutManager(new LinearLayoutManager(mContext));
        suggestionAdapter = new SearchSuggestionAdapter();
        mDataBinding.rvSuggestionList.setAdapter(suggestionAdapter);
        suggestionAdapter.setOnItemClickListener(this);

        mDataBinding.rvRecordList.setLayoutManager(new LinearLayoutManager(mContext));
        recordAdapter = new RecordAdapter();
        mDataBinding.rvRecordList.setAdapter(recordAdapter);
        recordAdapter.setOnItemClickListener(this);

        mDataBinding.rvCollectList.setLayoutManager(new LinearLayoutManager(mContext));
        collectAdapter = new CollectAdapter();
        mDataBinding.rvCollectList.setAdapter(collectAdapter);
        collectAdapter.setOnItemClickListener(this);

        mDataBinding.etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String search = charSequence.toString();
                if (TextUtils.isEmpty(search)) {
                    mDataBinding.rvSuggestionList.setVisibility(View.GONE);
                    mDataBinding.llCommon.setVisibility(View.VISIBLE);
                    mDataBinding.ivClear.setVisibility(View.INVISIBLE);
                    mDataBinding.tvSearchCancel.setVisibility(View.VISIBLE);
                    mDataBinding.tvSearchGo.setVisibility(View.GONE);
                } else {
                    mDataBinding.ivClear.setVisibility(View.VISIBLE);
                    mDataBinding.tvSearchCancel.setVisibility(View.GONE);
                    mDataBinding.tvSearchGo.setVisibility(View.VISIBLE);
                    getSearchSuggestion(search);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

//        setupKeyboardListener();
//        setupSearchFunction();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tvSearchGo) {//前往
            Intent intent = new Intent();
            intent.putExtra(Content.url, mDataBinding.etSearch.getText().toString());
            setResult(Content.SEARCH_TITLE_RESULT, intent);
            finish();
        } else if (id == R.id.ivClear) {//清空
            mDataBinding.etSearch.setText("");
        } else if (id == R.id.llHot) {//热门
            clearSelection();
            mDataBinding.ivHot.setVisibility(View.VISIBLE);
            mDataBinding.llHotFunc.setVisibility(View.VISIBLE);
        } else if (id == R.id.llBookmark) {//书签
            clearSelection();
            mDataBinding.ivBookmark.setVisibility(View.VISIBLE);
            mDataBinding.tvNoData.setVisibility(View.VISIBLE);
        } else if (id == R.id.llCollectUrl) {//收藏网址
            clearSelection();
            mDataBinding.ivCollectUrl.setVisibility(View.VISIBLE);
            getCollectData();
        } else if (id == R.id.tvAllDelete) {//全部删除
            if (recordAdapter.getItemCount() == 0) return;
            AppSpUtils.saveRecordList(new ArrayList<>());
            ToastUtils.showShort(getString(R.string.delete_suc));
            getRecordData();
        }
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == hotAdapter) {
            Intent intent = new Intent();
            intent.putExtra(Content.url, hotAdapter.getItem(position).getUrl());
            setResult(Content.SEARCH_URL_RESULT, intent);
            finish();
        } else if (adapter == suggestionAdapter) {
            if (suggestionAdapter.getItem(position).isRecord()) {
                Intent intent = new Intent();
                intent.putExtra(Content.url, suggestionAdapter.getItem(position).getUrl());
                setResult(Content.SEARCH_URL_RESULT, intent);
                finish();
            } else {
                Intent intent = new Intent();
                intent.putExtra(Content.url, suggestionAdapter.getItem(position).getTitle());
                setResult(Content.SEARCH_TITLE_RESULT, intent);
                finish();
            }
        } else if (adapter == recordAdapter) {
            Intent intent = new Intent();
            intent.putExtra(Content.url, recordAdapter.getItem(position).getUrl());
            setResult(Content.SEARCH_URL_RESULT, intent);
            finish();
        } else if (adapter == collectAdapter) {
            Intent intent = new Intent();
            intent.putExtra(Content.url, collectAdapter.getItem(position).getUrl());
            setResult(Content.SEARCH_URL_RESULT, intent);
            finish();
        }
    }

    @Override
    protected void initData() {
        List<HomeBean> listHot = new ArrayList<>();
        listHot.add(new HomeBean("百度", R.drawable.bd, "https://www.baidu.com"));
        listHot.add(new HomeBean("头条新闻", R.drawable.ttxw, "http://www.toutiao.com/"));
        listHot.add(new HomeBean("淘宝", R.drawable.tb, "https://www.taobao.com/"));
        listHot.add(new HomeBean("京东", R.drawable.jd, "https://www.jd.com/"));
        listHot.add(new HomeBean("天气", R.drawable.tq, "https://m.baidu.com/s?word=%E5%A4%A9%E6%B0%94"));
        listHot.add(new HomeBean("新浪新闻", R.drawable.xlxw, "https://news.sina.com.cn/"));
        hotAdapter.setList(listHot);

        getRecordData();
    }

    private void getRecordData() {
        List<RecordBean> listSp = AppSpUtils.getRecordList();
        if (listSp != null && !listSp.isEmpty()) {
            recordAdapter.setList(listSp);
            mDataBinding.rvRecordList.setVisibility(View.VISIBLE);
            mDataBinding.tvRecordNoData.setVisibility(View.GONE);
        } else {
            recordAdapter.setList(new ArrayList<>());
            mDataBinding.rvRecordList.setVisibility(View.GONE);
            mDataBinding.tvRecordNoData.setVisibility(View.VISIBLE);
        }
    }

    private void getCollectData() {
        List<CollectBean> collectList = AppSpUtils.getCollectList();
        if (collectList != null && !collectList.isEmpty()) {
            collectAdapter.setList(collectList);
            mDataBinding.rvCollectList.setVisibility(View.VISIBLE);
            mDataBinding.tvNoData.setVisibility(View.GONE);
        } else {
            collectAdapter.setList(new ArrayList<>());
            mDataBinding.rvCollectList.setVisibility(View.GONE);
            mDataBinding.tvNoData.setVisibility(View.VISIBLE);
        }
    }

    private void getSearchSuggestion(String search) {
        try {
            String url = "https://m.baidu.com/sugrec?pre=1&prod=wise&wd=" + URLEncoder.encode(search, "UTF-8");
            OkHttpUtils.getInstance().get(url, new OkHttpUtils.HttpCallback() {
                @Override
                public void onSuccess(String result) {
                    Log.e("TAG", result);
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        JSONArray jsonArray = jsonObject.optJSONArray("g");
                        List<SearchSuggestionBean> list = new ArrayList<>();
                        List<RecordBean> listSp = AppSpUtils.getRecordList();
                        if (listSp != null && listSp.size() > 0) {
                            for (RecordBean recordBean : listSp) {
                                if (recordBean.getTitle().contains(search)) {
                                    list.add(new SearchSuggestionBean(true, recordBean.getTitle(), recordBean.getUrl()));
                                }
                            }
                        }
                        if (jsonArray != null) {
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject item = jsonArray.getJSONObject(i);
                                String value = item.optString("q");
                                if (!TextUtils.isEmpty(value)) {
                                    list.add(new SearchSuggestionBean(false, value, ""));
                                }
                            }
                        }
                        suggestionAdapter.setList(list);
                        mDataBinding.rvSuggestionList.setVisibility(View.VISIBLE);
                        mDataBinding.llCommon.setVisibility(View.GONE);
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                }

                @Override
                public void onFailure(String error) {
                    mDataBinding.rvSuggestionList.setVisibility(View.GONE);
                    mDataBinding.llCommon.setVisibility(View.VISIBLE);
                }
            });
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    private void setupKeyboardListener() {
        // 监听键盘显示/隐藏
        ViewCompat.setOnApplyWindowInsetsListener(getWindow().getDecorView(), (v, insets) -> {
            int imeHeight = insets.getInsets(WindowInsetsCompat.Type.ime()).bottom;
            int systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()).bottom;

            if (imeHeight > systemBars) {
                // 键盘显示
                isKeyboardVisible = true;
                if (mDataBinding.llKeyboard.getVisibility() == View.VISIBLE) {
                    adjustSearchLayoutPosition(imeHeight);
                }
            } else {
                // 键盘隐藏
                isKeyboardVisible = false;
                hideSearchLayout();
            }

            return insets;
        });
    }

    private void adjustSearchLayoutPosition(int keyboardHeight) {
        // 计算搜索布局位置
        int[] location = new int[2];
        mDataBinding.llKeyboard.getLocationOnScreen(location);

        // 设置搜索布局在键盘上方
        mDataBinding.llKeyboard.setTranslationY(-keyboardHeight);
    }

    private void setupSearchFunction() {
        // 设置搜索框焦点变化监听
        mDataBinding.etSearch.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                showSearchLayout();
            }
        });
    }

    private void showSearchLayout() {
        mDataBinding.llKeyboard.setVisibility(View.VISIBLE);

        // 显示键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mDataBinding.llKeyboard, InputMethodManager.SHOW_IMPLICIT);
    }

    private void hideSearchLayout() {
        mDataBinding.llKeyboard.setVisibility(View.GONE);

        // 隐藏键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mDataBinding.llKeyboard.getWindowToken(), 0);
    }

    private void clearSelection() {
        mDataBinding.ivHot.setVisibility(View.INVISIBLE);
        mDataBinding.ivBookmark.setVisibility(View.INVISIBLE);
        mDataBinding.ivCollectUrl.setVisibility(View.INVISIBLE);
        mDataBinding.llHotFunc.setVisibility(View.GONE);
        mDataBinding.rvBookmarkList.setVisibility(View.GONE);
        mDataBinding.rvCollectList.setVisibility(View.GONE);
        mDataBinding.tvNoData.setVisibility(View.GONE);
    }

}